package com.ruoyi.system.controller;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONObject;
import com.google.gson.JsonObject;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.OrderCodeUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.ISysExpressService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import static com.ruoyi.system.service.impl.SysMemberRaiServiceImpl.convertToDate;

/**
 * 订单快递关联Controller
 * 
 * @author ruoyi
 * @date 2025-04-25
 */
@Api("订单快递关联")
@RestController
@RequestMapping("/system/express")
public class SysExpressController extends BaseController
{
    @Autowired
    private ISysExpressService sysExpressService;
    @Autowired
    private SysStoreMapper sysStoreMapper;
    @Autowired
    private SysMemberRaiMapper sysMemberRaiMapper;
    @Autowired
    private MemberRaiOrderMapper memberRaiOrderMapper;
    @Autowired
    private SysStoreStockMapper sysStoreStockMapper;
    @Autowired
    private SysMemberMapper sysMemberMapper;
    @Autowired
    private SysStockDetailsMapper sysStockDetailsMapper;

    /**
     * 查询订单快递关联列表
     */
    @ApiOperation("查询订单快递关联列表")
    // @PreAuthorize("@ss.hasPermi('system:express:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysExpress sysExpress)
    {
        startPage();
        List<SysExpress> list = sysExpressService.selectSysExpressList(sysExpress);
        for (SysExpress item : list) {
            //门店信息
            SysStore sysStore = sysStoreMapper.selectSysStoreById(item.getStoreId());
            item.setStoreName(sysStore.getStoreName());
        }
        return getDataTable(list);
    }

    /**
     * 导出订单快递关联列表
     */
    @ApiOperation("导出订单快递关联列表")
    // @PreAuthorize("@ss.hasPermi('system:express:export')")
    @Log(title = "订单快递关联", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysExpress sysExpress)
    {
        List<SysExpress> list = sysExpressService.selectSysExpressList(sysExpress);
        ExcelUtil<SysExpress> util = new ExcelUtil<SysExpress>(SysExpress.class);
        util.exportExcel(response, list, "订单快递关联数据");
    }

    /**
     * 获取订单快递关联详细信息
     */
    @ApiOperation("获取订单快递关联详细信息")
    // @PreAuthorize("@ss.hasPermi('system:express:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(sysExpressService.selectSysExpressById(id));
    }

    /**
     * 新增订单快递关联  发货
     */
    @ApiOperation("新增订单快递关联")
    // @PreAuthorize("@ss.hasPermi('system:express:add')")
    @Log(title = "订单快递关联", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysExpress sysExpress)
    {
        // express_way 根据物流方式来判断发货后扣除库存
        // TODO 发货成功后扣除库存 （暂不弄）
        // 自提 需要按订单的商品规格对应的商品数量乘以购买数量去扣除对应门店商品的可用库存
//        if ("1".equals(sysExpress.getExpressWay())){
//
//        }
        if (ObjectUtils.isEmpty(sysExpress.getRaiId()) || ObjectUtils.isEmpty(sysExpress.getExpressWay())) {
            return error("权益信息、物流方式不能为空");
        }
        // 修改会员订单状态为已兑现
        SysMemberRai sysMemberRaiRes = sysMemberRaiMapper.selectSysMemberRaiById(sysExpress.getRaiId());
        if (sysMemberRaiRes == null) {
            return AjaxResult.error("权益信息不存在");
        }
        MemberRaiOrder memberRaiOrder = memberRaiOrderMapper.selectMemberRaiOrderById(sysExpress.getRaiOrderId());
        // TODO 根据领取方式 需要按订单的商品数量去扣除对应门店商品的可用库存 (完成)
        // 判断领取方式是否为0 门店领取
        if (sysExpress.getExpressWay().equals("0")){
            // 获取会员配置中的领取数量
            SysMemberRai sysMemberRais = sysMemberRaiMapper.selectSysMemberRaiById(sysExpress.getRaiId());
            int raiNum = Integer.parseInt(sysMemberRais.getRaiNum());
            SysStoreStock sysStoreStock = new SysStoreStock();
            sysStoreStock.setGoodsId(sysExpress.getGoodsId());
            sysStoreStock.setStoreId(sysExpress.getStoreId());
            List<SysStoreStock> sysStoreStocks = sysStoreStockMapper.selectSysStoreStockList(sysStoreStock);
            // 判断是否有库存
            if (!sysStoreStocks.isEmpty()){
                for (SysStoreStock item : sysStoreStocks){
                    // 判断库存数量是否大于0
                    if (Integer.parseInt(item.getStockNum()) > 0){
                        int stockNum = Integer.parseInt(item.getStockNum());
                        stockNum = stockNum - raiNum;
                        item.setStockNum(String.valueOf(stockNum));
                        sysStoreStockMapper.updateSysStoreStock(item);
                        // 库存详情减少
                        SysStockDetails sysStockDetails = new SysStockDetails();

                        sysStockDetails.setGoodsId(sysExpress.getGoodsId());
                        sysStockDetails.setStoreId(sysExpress.getStoreId());
                        List<SysStockDetails> sysStockDetails1 = sysStockDetailsMapper.selectSysStockDetailsList(sysStockDetails);
                        int i = 0;
                        // 判断是否有库存详情
                        if (!sysStockDetails1.isEmpty()){
                            SysStockDetails kc = sysStockDetails1.get(0);
                            i = Integer.parseInt(kc.getRemainingNum()) - raiNum;
                        }else {
                            SysStoreStock stockParam = new SysStoreStock();
                            stockParam.setGoodsId(sysExpress.getGoodsId());
                            stockParam.setStoreId(sysExpress.getStoreId());
                            List<SysStoreStock> sysStoreStocks1 = sysStoreStockMapper.selectSysStoreStockList(stockParam);
                            // 判断是否有库存
                            if (!sysStoreStocks1.isEmpty()){
                                SysStoreStock sysStoreStock1 = sysStoreStocks1.get(0);
                                i = Integer.parseInt(sysStoreStock1.getStockNum()) - raiNum;
                            }
                        }
                        sysStockDetails.setAdjustType("2");
                        sysStockDetails.setAdjustNum(raiNum + "");
                        sysStockDetails.setRemainingNum(String.valueOf(i));
                        sysStockDetails.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
                        sysStockDetailsMapper.insertSysStockDetails(sysStockDetails);
                    }
                }
            }
        }

        MemberRaiOrder param = new MemberRaiOrder();
        param.setRaiStatus("1");
        param.setRaiId(sysExpress.getRaiId());
        param.setId(sysExpress.getId());
        memberRaiOrderMapper.updateMemberRaiOrder(param);
        sysExpress.setOrderId(OrderCodeUtils.getOrderCode("S"));
        return toAjax(sysExpressService.insertSysExpress(sysExpress));
    }

    /**
     * 修改订单快递关联
     */
    @ApiOperation("修改订单快递关联")
    // @PreAuthorize("@ss.hasPermi('system:express:edit')")
    @Log(title = "订单快递关联", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysExpress sysExpress)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        sysExpress.setUpdateBy(user.getUserId() + "");
        return toAjax(sysExpressService.updateSysExpress(sysExpress));
    }

    /**
     * 删除订单快递关联
     */
    @ApiOperation("删除订单快递关联")
    // @PreAuthorize("@ss.hasPermi('system:express:remove')")
    @Log(title = "订单快递关联", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(sysExpressService.deleteSysExpressByIds(ids));
    }
}
